package com.wtwd.device.handler;


import com.alibaba.fastjson.JSONObject;
import com.wtwd.device.constant.MsgTypeEnum;
import com.wtwd.device.model.DeviceSession;
import com.wtwd.device.netty.LocalSessions;
import com.wtwd.device.protocol.AppProtocol;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MsgHandler implements IMsgHandler {

    @Override
    public void processMessage(AppProtocol protocol, Channel channel) {
        try {
            ProcessMessageHandler handler = MsgHandlerFactory.createProcessMessageHandler(protocol.getCmdName());
            AppProtocol result = handler.processMsg(protocol, channel);
            if (result == null) return;
            ChannelFuture channelFuture = channel.writeAndFlush(result);//某部分消息服务器收到直接进行应答
        } catch (Exception e) {
            log.error("协议处理异常{}-{}", JSONObject.toJSONString(protocol), e.getMessage());
        }
    }

    @Override
    public void sendMessage(AppProtocol protocol) {
        String cmdName = protocol.getCmdName();
        DeviceSession session;
        if (MsgTypeEnum.APP_LOGIN.getCmdName().equals(cmdName)) {//
            session = LocalSessions.deviceLoginSession(protocol.getImei());
        } else {
            session = LocalSessions.getDeviceSession(protocol.getImei());
        }
        ChannelFuture channelFuture = session.getChannel().writeAndFlush(protocol);
        channelFuture.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                if (channelFuture.isSuccess()) {
                    log.info("直接下发消息,成功-{}", protocol.toString());
                } else {
                    log.info("直接下发消息,失败-{},{}", protocol.toString());
                }
            }
        });

    }


}
